package com.yinhe.music.yhmusic.base;

import com.yinhe.music.yhmusic.network.schedulers.BaseSchedulerProvider;
import com.yinhe.music.yhmusic.network.schedulers.SchedulerProvider;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * 基础presenter层
 *
 * @param <M>
 * @param <V>
 * @author 何晓华
 */
public abstract class BasePresenter<M extends IBaseModel, V extends IBaseView> {

    /**
     * 线程切换
     */
    public BaseSchedulerProvider schedulerProvider;

    public CompositeDisposable mDisposable;

    /**
     * 采用了弱引用的方式去保存这个View的对象引用,减少内存泄露的可能性
     */
    private WeakReference<V> mViewRef;

    public M mModel;


    public void attachModelView(M pModel, V pView) {

        mViewRef = new WeakReference<>(pView);

        this.mModel = pModel;

        this.schedulerProvider = SchedulerProvider.getInstance();
        mDisposable = new CompositeDisposable();
    }


    public V getView() {
        if (isAttach()) {
            return mViewRef.get();
        } else {
            return null;
        }
    }

    /**
     * 取消网络请求
     */
    public void dispose() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }

    }

    private boolean isAttach() {
        return null != mViewRef && null != mViewRef.get();
    }


    public void onDetach() {
        if (null != mViewRef) {
            mViewRef.clear();
            mViewRef = null;
        }
    }

    protected void addSubscription(Disposable disposable) {
        if (mDisposable == null) {
            mDisposable = new CompositeDisposable();
        }
        mDisposable.add(disposable);
    }
}
